package org.jeecg.modules.meta.controller;

import cn.hutool.core.date.DateUtil;
import org.jeecg.common.api.vo.Result;
import org.jeecg.desen.cretab.service.DesensDatabaseCreateService;
import org.jeecg.modules.meta.service.MetaSynService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.sql.DataSource;
import java.sql.ResultSet;

import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;

/**
 * 元数据平台数据改动提醒接收控制器
 */
@Controller
@RequestMapping("/metaSyn")
public class MetaSynController {

    @Autowired
    MetaSynService metaSynService;

    @Autowired
    @Qualifier("hiveDruidDataSource")
    DataSource druidDataSource;

    @Autowired
    DesensDatabaseCreateService desensDatabaseCreateService;

    /**
     * 全量更新提醒
     *
     * @author ls
     * @Date 2019-05-06
     */
    @RequestMapping("/all")
    @ResponseBody
    public Result metaSynAllNotice() {
        return Result.ok(metaSynService.synMetaAll());
    }

    /**
     * 制定日期更新提醒
     *
     * @author ls
     * @Date 2019-05-28
     */
    @RequestMapping("/toDate")
    @ResponseBody
    public Result metaSynToDateNotice(String synDate) {
        Date date;
        if (StringUtils.isEmpty(synDate)) {
            date = new Date();
        } else {
            date = DateUtil.parse(synDate);
        }
        return Result.ok(metaSynService.synMetaTime(date));
    }

    /**
     * 全量更新提醒
     *
     * @author ls
     * @Date 2019-05-06
     */
    @RequestMapping("/table")
    @ResponseBody
    public Result table(String synDate) {
        return Result.ok(desensDatabaseCreateService.createHiveTableByStatus(new Date()));
    }

    @RequestMapping("/testTable")
    @ResponseBody
    public Result<Object> testTable() throws SQLException {
        List<String> list = new ArrayList<String>();
        // Statement statement = jdbcDataSource.getConnection().createStatement();
        /*Statement statement = druidDataSource.getConnection().createStatement();
        String sql = "show tables";
        ResultSet res = statement.executeQuery(sql);
        while (res.next()) {
            list.add(res.getString(1));
        }*/

        List<Map<String, String>> maps = new ArrayList<>();
        Statement statement = druidDataSource.getConnection().createStatement();

        String hiveSql = " desc testNew.test ";//desc formatted test
        ResultSet resultSet = statement.executeQuery(hiveSql);
        while (resultSet.next()) {
            Map<String, String> fieldMaps = new HashMap<>();
            fieldMaps.put(resultSet.getString(1), resultSet.getString(2));
            maps.add(fieldMaps);
        }
        return Result.ok(maps);

    }

}
